using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using System.Diagnostics;

namespace FullTrustFeature
{
    class FullTrustFeatureReceiver : SPFeatureReceiver
    {
        private void ApplyWebConfigModificationsToFarm(SPWebApplication webApp)
        {
            try
            {
                webApp.Farm.Services.GetValue<SPWebService>().ApplyWebConfigModifications();
            }
            catch (System.UnauthorizedAccessException ex)
            {
                SPSecurity.RunWithElevatedPrivileges(delegate
                {
                    EventLog.WriteEntry(this.GetType().FullName, string.Format("Exception occured running the FeatureReceiver when ApplyWebConfigModifications was called.{0}If you give WSS_WPG user account full permission to the config folder the error will disappear!{0}{1}", Environment.NewLine, ex.ToString()), EventLogEntryType.Error);
                });
                throw;
            }
        }

        private string Owner
        {
            get
            {
                return this.GetType().FullName + ", " + this.GetType().Assembly.FullName;
            }
        }

        private const string TRUSTNODE = "trust";
        private const string FULLVALUE = "Full";

        private SPWebConfigModification AddTrustLevelFull_modification
        {
            get
            {
                SPWebConfigModification modification = new SPWebConfigModification("level", "configuration/system.web/trust");
                modification.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureAttribute;
                modification.Value = FULLVALUE;
                modification.Owner = Owner;
                return modification;
            }
        }


        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            SPWebApplication webapp = properties.Feature.Parent as SPWebApplication;
            if (webapp == null) return;

            webapp.WebConfigModifications.Add(AddTrustLevelFull_modification);

            webapp.Update(); // Important. Otherwise webconfigmods can be removed upon activating other features
            ApplyWebConfigModificationsToFarm(webapp);
        }

        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            SPWebApplication webapp = properties.Feature.Parent as SPWebApplication;
            if (webapp == null) return;

            for (int idx = webapp.WebConfigModifications.Count - 1; idx >= 0; idx--)
            {
                try
                {
                    SPWebConfigModification conmod = webapp.WebConfigModifications[idx];
                    if (string.Compare(conmod.Owner, Owner, true) == 0)
                    {
                        webapp.WebConfigModifications.RemoveAt(idx);
                    }
                }
                catch (Exception ex)
                {
                }
            }

            webapp.Update(); // Important
            ApplyWebConfigModificationsToFarm(webapp);

        }

        public override void FeatureInstalled(SPFeatureReceiverProperties properties)
        {
        }

        public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
        {
        }
    }
}
